<?php

namespace app\common\model\xilujob;

use think\Exception;
use think\Log;
use think\Model;
use traits\model\SoftDelete;
use function fast\array_get;

class EnterpriseInfo extends Model
{
    use SoftDelete;

    const GEO_STATUS_PARSING = 0;
    const GEO_STATUS_PARSED = 1;
    const GEO_STATUS_FAILED = 2;

    // 表名
    protected $name = 'xilujob_enterprise_info';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    protected $append = [
        //'benefit_ids'
    ];

    public static function init() {
        self::beforeUpdate(function($model){
            $changedData = $model->getChangedData();
            if(isset($changedData['address'])) {
                $model->geo_status = self::GEO_STATUS_PARSING;
            }
        });
    }

    public function getBenefitIdsAttr($value, $data) {
        $ids = [];
        foreach ($this->benefits as $benefit) {
            $ids[] = $benefit->id;
        }
        return implode(',',$ids);
    }

    public function user() {
        return $this->belongsTo('User', 'user_id','id');
    }

    public function benefits() {
        return $this->belongsToMany('Benefit',EnterpriseBenefit::class,'benefit_id','enterprise_id');
    }

    public function city() {
        return $this->belongsTo('Area', 'city_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    /*职位预览使用*/
    public function companyProperties() {
        return $this->belongsTo('CompanyProperties', 'company_type_id');
    }

    public function companyScale() {
        return $this->belongsTo('CompanyScale', 'company_scale_id');
    }

    public function industryCategory() {
        return $this->belongsTo('IndustryCategory', 'industry_category_id');
    }

    /*************************************前端*****************************************/
    /**
     * 提交企业认证信息
     * @param Model $enterpriseModel  Member CompanyProfile Trainer LabourShop其一
     * @param array $params
     * @return array
     * @throws Exception
     * @throws \think\exception\DbException
     */
    public static function submitEnterpriseAuditInfo($enterpriseModel, $params) {
        if(!$enterpriseModel instanceof CompanyProfile){
            $enterpriseModel = CompanyProfile::get($enterpriseModel);
        }
        $info = static::get(['company_id'=>$enterpriseModel->id]);
        if(!$info) {
            throw new Exception('无企业信息数据');
        }
        try {
            $params = array_intersect_key($params,array_flip(['license_img','company_name']));
            $ret = $info->validate([
                'license_img|营业执照' => ['require'],
                'company_name|公司全称' => ['require', 'length:0,50'],
            ])->save($params);
            if ($ret === false) {
                throw new Exception($info->getError());
            }

            if(get_addon_config('xilujob')['enterprise_audit_switch']) {
                if (in_array($enterpriseModel->audit_status, [CompanyProfile::ENTERPRISE_AUDIT_STATUS_NONE, CompanyProfile::ENTERPRISE_AUDIT_STATUS_FAILED,]) || ($enterpriseModel->audit_status == CompanyProfile::ENTERPRISE_AUDIT_STATUS_PASSED && $info->getChangedData())) {
                    // 有修改 ， 改状态为待审核
                    $enterpriseModel->save(['audit_status'=> CompanyProfile::ENTERPRISE_AUDIT_STATUS_WAITING]);
                }
            }else {
                //自动过审
                $enterpriseModel->save(['audit_status'=>CompanyProfile::ENTERPRISE_AUDIT_STATUS_PASSED]);
            }
            return ['info'=>$info,'model'=>$enterpriseModel];
        }catch (\Exception $e) {
            Log::error($e->getMessage()."\n".$e->getTraceAsString());
            throw new Exception($e->getMessage());
        }
    }
    /**
     * 编辑企业信息
     * @param Model $enterpriseInfo
     * @param array $params
     * @return EnterpriseInfo
     * @throws Exception
     * @throws \think\exception\DbException
     */
    public static function saveInfo($enterpriseInfo, $params) {
        if(!$enterpriseInfo instanceof EnterpriseInfo) {
            $enterpriseInfo = EnterpriseInfo::get(['company_id'=>$enterpriseInfo]);
        }
        if(!$enterpriseInfo) {
            throw new Exception(__('no record'));
        }
        $validator = new \app\common\validate\xilujob\EnterpriseInfo();
        if(!$validator->check($params)) {
            throw new Exception($validator->getError());
        }
        $infoParams = array_intersect_key($params, array_flip([
            'full_name','industry_category_id','contact_person','contact_phone','contact_email','address','logo',
            'company_scale_id','company_type_id','intro','environment_images','city_id'
        ]));
        try {
            $benefitIds = array_get($params,'benefit_ids');
            if($benefitIds) {
                $insertBenefits = [];
                $benefitIds = is_array($benefitIds) ? $benefitIds : explode(',', $benefitIds);
                EnterpriseBenefit::whereNotIn('benefit_id', $benefitIds)->where('enterprise_id', $enterpriseInfo->id)->delete();
                foreach ($benefitIds as &$benefitId) {
                    if(EnterpriseBenefit::where('enterprise_id', $enterpriseInfo->id)->where('benefit_id',$benefitId)->count()<1)
                        $insertBenefits[] = ['enterprise_id'=>$enterpriseInfo->id, 'benefit_id'=>$benefitId];
                }
                if($insertBenefits) {
                    $cb = new EnterpriseBenefit();
                    $cb->saveAll($insertBenefits);
                }
            }else {
                EnterpriseBenefit::where('enterprise_id', $enterpriseInfo->id)->delete();
            }
            $images = array_get($infoParams,'environment_images',null);
            if($images!==null) {
                $infoParams['environment_images'] = is_array($images) ? implode(',', $images) : $images;
            }

            $lat = array_get($params,'lat');
            $lng = array_get($params,'lng');
            if(($lat && $lat != $enterpriseInfo->lat) || ($lng && $lng != $enterpriseInfo->lng)){
                $geohashTool = new \app\common\library\xilujob\Geohash();
                $geohash = $geohashTool->encode($lat, $lng, 8);
                $infoParams['geo_status'] = self::GEO_STATUS_PARSED;
                $infoParams['geohash'] = $geohash;
            }

            $ret = $enterpriseInfo->save($infoParams);
            $enterpriseInfo->save(['info_complete'=>self::calcInfoComplete($enterpriseInfo)]);
            if($ret===false) {
                throw new Exception($enterpriseInfo->getError());
            }
            return $enterpriseInfo;
        }catch (\Exception $e) {
            Log::error($e->getMessage()."\n".$e->getTraceAsString());
            throw new Exception($e->getMessage());
        }
    }

    public static function calcInfoComplete(EnterpriseInfo $info) {
        $total = $complete = 0;
        $keys = ['company_name','industry_category_id','contact_person','contact_phone','contact_email', 'address','logo',
            'license_img', 'company_scale_id','company_type_id','intro','environment_images'];
        foreach ($keys as $key) {
            if($info->$key) {
                $complete++;
            }
            $total++;
        }
        if(EnterpriseBenefit::where('enterprise_id',$info->id)->count() > 0) {
            $complete++;
        }
        $total++;
        return intval($complete/$total*100);

    }
    
}
